#include <iostream>
#include <string>
#include "../comm/httplib.h"
#include "oj_control.hpp"
using namespace ns_ctrl;

using namespace httplib;

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        std::cout << "Usage:\n\t" << argv[0] << " [port]\n";
        return 1;
    }

    uint16_t port = std::stoi(argv[1]);

    /*********************
     * 用户可能的操作：
     *
     * 1、获取题目列表 /all_questions
     * 2、根据编号获取题目内容 (/question/100) 加编号
     * 3、使用判题功能(a、compile_and_run; b、测试用例)  /judge/100
     *
     **********************/

    /*********************
     * 1、题目的编号
     * 2、标题
     * 3、难度
     * 4、内容
     * 5、时间要求
     * 6、空间要求
     **********************/
    Server svr;
    Control ctrl;


    svr.Get("/all_questions", [&ctrl](const Request &req, Response &resp)
    { 
        std::string html;
        ctrl.AllQuestions(&html, req);
        resp.set_content(html, "text/html; charset=UTF-8"); 
    });

    svr.Get(R"(/question/(\d+))", [&ctrl](const Request &req, Response &resp)
    {
        // match[1] 表示正则表达式第一个括号内的内容
        // match[0] 表示匹配的整个字符串
        std::string number = req.matches[1];

        std::string html;
        ctrl.NumQuestion(number, &html, req);

        resp.set_content(html, "text/html; charset=UTF-8"); 
    });

    svr.Post(R"(/judge/(\d+))", [&ctrl](const Request &req, Response &resp)
    {
        std::string num = req.matches[1];
        std::string in_json = req.body;

        std::string out_json;
        ctrl.Judge(num, in_json, &out_json);
        resp.set_content(out_json, "application/json; charset=utf-8");
    });

    svr.Get("/login", [&ctrl](const Request &req, Response &resp)
    { 
        std::string html;
        ctrl.LoginHtml(&html);

        resp.set_content(html, "text/html; charset=UTF-8");
    });

    svr.Post("/login", [&ctrl](const Request &req, Response &resp)
    { 
        ctrl.login(req.body, resp);
    });

    svr.Get("/reg", [&ctrl](const Request &req, Response &resp)
    { 
        std::string html;
        ctrl.RegHtml(&html);

        resp.set_content(html, "text/html; charset=UTF-8");
    });

    svr.Post("/reg", [&ctrl](const Request &req, Response &resp)
    { 
        ctrl.Reg(req.body, resp);
    });

    svr.Get("/", [&ctrl](const Request &req, Response &resp)
    { 

        std::string html;
        ctrl.IndexHtml(&html, req);

        resp.set_content(html, "text/html; charset=UTF-8");
    });

    svr.Get("/AlreadyLogin", [&ctrl](const Request &req, Response &resp)
    { 

        std::string html;
        ctrl.AlreadyLoginHtml(&html, req);

        resp.set_content(html, "text/html; charset=UTF-8");
    });

    svr.set_base_dir("./wwwroot");

    // 要先注册处理函数，再监听
    // 再监听后注册处理函数已经太晚了
    svr.listen("0.0.0.0", port);
    return 0;
}